#include <iostream>
#include <thread>
#include <vector>

class TicketSystem
{
public:
    TicketSystem(int total) : tickets(total) {}

    void sellTicket()
    {
        if (tickets > 0)
        {
            // 模拟处理时间
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
            tickets--;
            std::cout << "售出1张票，剩余: " << tickets
                      << " (线程ID: " << std::this_thread::get_id() << ")\n";
        }
        else return;
    }

    int getRemaining() const { return tickets; }

private:
    int tickets;
};

int main()
{
    const int TOTAL_TICKETS = 1000;
    const int THREAD_NUM = 10;

    TicketSystem system(TOTAL_TICKETS);
    std::vector<std::thread> threads;

    for (int i = 0; i < THREAD_NUM; ++i)
    {
        threads.emplace_back([&system]()
                             {
            while (system.getRemaining() > 0) {
                system.sellTicket();
            } });
    }

    for (auto &t : threads)
    {
        t.join();
    }

    std::cout << "最终剩余票数: " << system.getRemaining() << std::endl;
    return 0;
}